package com.googlecode.perfectable.persistable.index.memory;

import java.util.Collection;
import java.util.function.Function;

import com.google.common.collect.HashMultimap;
import com.google.common.collect.Multimap;
import com.googlecode.perfectable.persistable.index.Index;
import com.googlecode.perfectable.persistable.session.Identifier;

public class MemoryIndex<T, X> implements Index<T, X> {

	private final Multimap<X, Identifier<? extends T>> contents = HashMultimap.create();
	private final Function<T, X> transformer;

	public MemoryIndex(Function<T, X> transformer) {
		this.transformer = transformer;
	}

	@Override
	public Collection<Identifier<? extends T>> scan(X expression) {
		return this.contents.get(expression);
	}

	@Override
	@SuppressWarnings("unchecked")
	// MARK WOW
	public <K> void insert(K entity, Identifier<? extends K> identity) {
		X discriminator = this.transformer.apply((T) entity);
		this.contents.put(discriminator, (Identifier<? extends T>) identity);
	}
}
